//
// Created by zlj on 2025/5/1.
//
#include "debug_uart.h"

void (*uart1_recv_callback)(void) = NULL;
UART_HandleTypeDef huart1;
uint8_t rx_data;  // 接收1字节数据

 int __io_putchar(int ch) {
     HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
     return ch;
 }

/**
 * 打印串口初始化
 */
void DEBUG_UART_Configuration(void) {

    __HAL_RCC_USART1_CLK_ENABLE();
    __HAL_RCC_GPIOA_CLK_ENABLE();

    GPIO_InitTypeDef GPIO_InitStructure;
    //RX PA9
    GPIO_InitStructure.Pin = DEBUG_UART_RX_PIN;
    GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
    GPIO_InitStructure.Mode = GPIO_MODE_AF_PP; // 复用推挽输出
    HAL_GPIO_Init(DEBUG_UART_RX_PORT, &GPIO_InitStructure);

    //TX PA10
    GPIO_InitStructure.Pin = DEBUG_UART_TX_PIN;
    GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
    GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;                      // 复用推挽输出
    HAL_GPIO_Init(DEBUG_UART_RX_PORT, &GPIO_InitStructure);

    huart1.Instance = USART1;
    huart1.Init.BaudRate = 115200;
    huart1.Init.WordLength = UART_WORDLENGTH_8B;
    huart1.Init.StopBits = UART_STOPBITS_1;
    huart1.Init.Parity = UART_PARITY_NONE;
    huart1.Init.Mode = UART_MODE_TX_RX;
    huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    huart1.Init.OverSampling = UART_OVERSAMPLING_16;

    if (HAL_UART_Init(&huart1) != HAL_OK)
    {
        // 初始化失败，进入错误处理
        Error_Handler();
    }

    // NVIC 设置
    HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USART1_IRQn);
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart->Instance == USART1)
    {
        // 处理收到的数据 rx_data
        HAL_UART_Transmit(&huart1, &rx_data, 1, HAL_MAX_DELAY);  // 回显

        // 继续接收下一个字节
        HAL_UART_Receive_IT(&huart1, &rx_data, 1);
    }
}

/**
 * 中断
 */
void USART1_IRQHandler(void)
{

}